package com.lsc.Controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;

import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program: springboot_shiro
 * @description: Controller层
 * @author: 上河图
 * @create: 2020-09-29 12:40
 */
@Controller
public class shiroController {

    @RequestMapping("/toLogin")
    public String toLogin(String username, String password, Model model) {
        /*获取当前用户*/
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        /*一般都是拿唯一的标识当令牌的。*/
        try {
            subject.login(token);
            return "login";
            //封装错误信息
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户名不正确");
            return "index";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码不正确");
            return "index";
        }

    }

    /**
     * @Description: 用户登出并清除缓存（令牌）
     * @Param:
     * @return: 返回登出后的提示
     * @Author: 上河图
     * @Date: 2020/10/1/16:23
     */

    @RequestMapping("/loginout")
    public String loginout() {

        Subject currentSubject = SecurityUtils.getSubject();
        currentSubject.logout();

        return "index";
    }

    /**
     * @Description: 自定义一个401无授权的页面
     * @Param:
     * @return: 返回的是401的错误提示
     * @Author: 上河图
     * @Date: 2020/9/30/23:38
     */
    @RequestMapping("/Authorization")
    @ResponseBody
    public String Authorization() {

        return "此页面未经授权,不能访问";
    }

    /**
     * @Description: 添加
     * @Param: null
     * @return: 返回数据给add.html中
     * @Author: 上河图
     * @Date: 2020/9/29/12:52
     */
    @RequestMapping("User/add")
    public String add() {

        return "add";
    }

    /**
     * @Description: 更新测试
     * @Param: []
     * @return: 返回数据给update.html
     * @Author: 上河图
     * @Date: 2020/9/29/12:53
     */
    @RequestMapping("User/update")
    public String update() {

        return "update";
    }

}
